package com.shrio.controller;

import com.shrio.dao.UserDao;
import com.shrio.entity.User;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by luojie on 2018/3/27.
 */
@Controller
public class CreateIndexer {

    @Autowired
    private UserDao userDao;

    @RequestMapping("create")
    public void create() throws Exception{
        List<User> list = userDao.findAll();
        // Document对象集合。
        List<Document> docList = new ArrayList<Document>();
        // Document对象的引用，空指针。
        Document doc = null;
        for(User user : list){
            // 创建Document对象，同时要创建Field对象。
            doc = new Document();
            // 根据需求创建不同类型的Field。
            Field id = new TextField("id", user.getId().toString(), Field.Store.YES);

            Field name = new TextField("name", user.getUsername(), Field.Store.YES);
            doc.add(id);
            doc.add(name);
            docList.add(doc);
        }

        // 使用StandardAnalyzer对文档进行分词。
        Analyzer analyzer = new StandardAnalyzer();

// 创建索引库目录。
        Directory directory = FSDirectory.open(new File("G:\\index"));

// 创建IndexWriterConfig对象
        IndexWriterConfig cfg = new IndexWriterConfig(Version.LATEST, analyzer);

// 创建IndexWriter对象
        IndexWriter writer = new IndexWriter(directory, cfg);

// 通过IndexWriter对象添加文档对象（document）
        for (Document document : docList) {
            writer.addDocument(document);
        }

// 关闭IndexWriter
        writer.close();
    }

    @RequestMapping("search")
    public void search() throws Exception{
        Directory dir= FSDirectory.open(new File("E:\\luceneData"));
        //创建索引读取器
        IndexReader reader= DirectoryReader.open(dir);
        //创建索引查询器
        IndexSearcher is=new IndexSearcher(reader);
        // 标准分词器
        Analyzer analyzer=new StandardAnalyzer();
        //开始查询解析
        QueryParser parser=new QueryParser("name", analyzer);
        Query query=parser.parse("user2");

        long start=System.currentTimeMillis();
        TopDocs hits=is.search(query, 10);
        long end=System.currentTimeMillis();
        System.out.println("匹配，总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录");
        for(ScoreDoc scoreDoc:hits.scoreDocs){
            Document doc=is.doc(scoreDoc.doc);
            System.out.println(doc.get("fullPath"));
        }
        reader.close();
    }
}
